import config from '../config';

define(function(require, exports, module) {
    var angular = require('angular');
    require("@yunke/jquery_pagination");
    require('angular-ui');
    require('../common/nav');
    require("../../plugins/select2/select2");
    require('../abnormal/abnormal-common');
    require("uploader");
    var util = require('@yunke/core/util').default;
    var ui = require("@yunke/core/ui");
    var moment = require('moment');

    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    angular.module('SpecialInvoice', ['ngUI', 'myNav', 'select2', 'AbnormalCommonService'])
            .controller('specialInvoiceListCtrl', ['$scope', 'abnormalCommonService', 'appservice', function($scope, abnormalCommonService, appservice) {
                appservice.name = '明源云客-特批发票';
                    ui.loading('', '正在加载…');
                    $scope.invoices = [];
                    $scope.sn = 0;
                    $scope.filterDataCities = [{
                            areaName: '全部', selected: true, areaId: ''
                        }];
                    //获取合同区域列表
                    abnormalCommonService.getContractAreas(function(data) {
                        $.merge($scope.filterDataCities, data);
                        $scope.$applyAsync();
                    });

                    $scope.changeCity = function(city) {
                        $scope.query.execute();
                    }
                    $scope.filterFulfils = [{
                            name: '全部', selected: true, value: ''
                        }, {
                            name: '是', value: '1'
                        }, {
                            name: '否', value: '0'
                        }];


                    $scope.changeFulfil = function(fulfil) {
                        $scope.query.execute();
                    }

                    //查询条件
                    $scope.query = {
                        keyword: '',
                        execute: function(page) {
                            var parms = {keyword: this.keyword};
                            parms.pageIndex = page || 1;
                            parms.pageSize = config.pager().pageSize;
                            parms.sortBy = 'created_on';
                            parms.sortAsc = 'false';

                            //收集过滤条件
                            var filterCity = $.grep($scope.filterDataCities, function(o, n) {
                                return o.selected == true;
                            })
                            if (filterCity.length) {
                                parms.areaId = filterCity[0].areaId;
                            }

                            var filterFulfil = $.grep($scope.filterFulfils, function(o, n) {
                                return o.selected == true;
                            })
                            if (filterFulfil.length) {
                                parms.fulfil = filterFulfil[0].value;
                            }

                            var url = api_prefix + "/special-approval-invoice/get-special-approval-invoice-list";
                            util.myAjax({
                                url: url,
                                type: "GET",
                                cache: false,
                                data: parms,
                                context: this,
                                success: function(json) {
                                    if (json.retCode == 0) {
                                         // 特批类型
                                        var categoryList = $scope.getCategoryList();
                                        $(json.data.items).each(function(idx,item){
                                            $(categoryList).each(function(idx2,item2){
                                                if(item2.id == item.category){
                                                    item.category_name = item2.value;
                                                    return false;
                                                }
                                            });
                                        });

                                        $scope.invoices = json.data.items;
                                        $scope.$applyAsync();

                                        $scope.startPageIndex = (parms.pageIndex - 1)*10;
                                        $('#pagination').pagination(json.data.total, {
                                            current_page: parms.pageIndex - 1,
                                            num_edge_entries: 1, //边缘页数
                                            num_display_entries: 4, //主体页数
                                            callback: function(page_index, jq) {
                                                //page_index += 1; // 分页控件从 0 开始，后台从 1 开始
                                                $scope.startPageIndex = (page_index - 1)*10;
                                                $scope.query.execute(page_index);
                                                //if (isPagination === true && page_index !== service.pageIndex) {
                                                /*service.pageIndex = page_index;
                                                 service.doQuery(true);*/
                                                //}
                                            },
                                            items_per_page: config.pager().pageSize //每页显示1项
                                        });

                                    } else {
                                        util.alert(json.errMsg);
                                    }
                                },
                                complete: function() {
                                    ui.removeLoading();
                                }
                            });

                        }
                    };

                    $scope.saveInvoice = function(dialog, dialogScope) {
                        var url = api_prefix + "/special-approval-invoice/save-special-approval-invoice";
                        util.myAjax({
                            url: url,
                            type: "POST",
                            cache: false,
                            data: {item: dialogScope.data.item, attachmentList: dialogScope.data.attachmentList},
                            context: this,
                            success: function(json) {
                                if (json.retCode == 0) {
                                    dialogScope.data.special_approval_invoice_id = json.data;
                                    util.alert('保存成功');
                                } else {
                                    util.alert(json.errMsg);
                                }
                            },
                            complete: function() {
                                ui.removeLoading();
                                $scope.query.execute();
                            }
                        });
                    };
                    $scope.getEmptyInvoice = function(dialogScope) {
                        return {
                            item: {
                                special_approval_invoice_id: '',
                                invoice_no: '',
                                category: '',
                                category_temp:'',
                                promise_fulfil_time: '',
                                promise_fulfil_principle: '',
                                actual_fulfil_time: '',
                                comment: '',
                                created_on: '',
                                created_by: '',
                                modified_on: '',
                                modified_by: '',
                                principal_name: ''
                            },
                            categoryList: $scope.getCategoryList(),
                            attachmentList: [],
                            ddlConfigInvoice: {
                                allowClear: false,
                                placeholder: '',
                                ajax: {
                                    url: api_prefix + "/invoice/get-invoice-list-for-sepcial-invoice-select2",
                                    dataType: 'json',
                                    delay: 250,
                                    data: function(term, page) {
                                        return {
                                            keyword: term,
                                            limit: 10
                                        };
                                    },
                                    results: function(data, page) {
                                        return {
                                            results: data.data
                                        };
                                    },
                                    cache: true
                                },
                                escapeMarkup: function(markup) {
                                    return markup;
                                },
                                minimumInputLength: 1,
                                onchange2: function(newVal) {
                                },
                                templateResult: function(data) {
                                    return data;
                                },
                                templateSelection: function(data) {
                                    return data;
                                }
                            },
                            ddlConfigPrinciple: {
                                ajax: {
                                    url: api_prefix + "/erp-interface/get-users",
                                    dataType: 'json',
                                    delay: 250,
                                    data: function(term, page) {
                                        return {
                                            keyword: term,
                                            limit: 10
                                        };
                                    },
                                    results: function(data, page) {
                                        return {
                                            results: data.data
                                        };
                                    },
                                    cache: true
                                },
                                escapeMarkup: function(markup) {
                                    return markup;
                                },
                                minimumInputLength: 1,
                                templateResult: function(data) {
                                    return data;
                                },
                                templateSelection: function(data) {
                                    return data;
                                },
                                onchange2: function(data){
                                    dialogScope.data.item['principal_name'] = data.text;
                                }
                            },
                            delAttachment: function(data, id) {
                                $(data.attachmentList).each(function(idx, item) {
                                    if (item.document_id.toLowerCase() == id.toLowerCase()) {
                                        data.attachmentList.splice(idx, 1);
                                    }
                                });
                            },
                            changeCategory: function(data) {
                                if (typeof (data) == 'undefined') {
                                    return;
                                }
                                data.item.category_temp = data.item.category;
                            },
                        };
                    };


                    //确定并新增
                    var addAndSaveBtn = function($dialog,$dialogScope){
                        $($dialog.node).find('[i-id=ok]').after('<button type="button" i-id="okAdd" class="ui-dialog-autofocus" >确定并新增</button>');
                        $($dialog.node).find('[i-id=okAdd]').on('click',function(){
                            $dialogScope.saveAndAdd = true;
                            $($dialog.node).find('[i-id=ok]').trigger('click');
                            //保存上一次新增值
                            $scope.lastAddSpecialInvoice = $dialogScope.data;
                        });
                        $($dialog.node).find('[i-id=cancel]').on('click',function(){
                            $dialogScope.saveAndAdd = false;
                            $scope.ifLastAddNewSpecialInvoice = false;

                        });
                        $($dialog.node).find('[i-id=ok]').on('click',function(){
                            $scope.ifLastAddNewSpecialInvoice = false;
                        });
                    };

                    $scope.onCloseSpecialInvoice = function($dialogScope){
                        if($dialogScope.saveAndAdd === true){
                            $('#addSpecialInvoiceButton').trigger('click');
                            $scope.ifLastAddNewSpecialInvoice = true;
                        }
                    };


                    $scope.onInvoiceEditShow = function(row, dialog, dialogScope) {
                        ui.loading('', '正在加载…');

                        addAndSaveBtn(dialog, dialogScope);

                        dialogScope.data = $scope.getEmptyInvoice(dialogScope);
                        if (row == null) {
                            // 新增模式
                            dialogScope.loading = false;
                            ui.removeLoading();

                            //如果是新增继续添加
                            if($scope.ifLastAddNewSpecialInvoice){
                                setTimeout(function () {
                                    $('#invoice_no').data('select2').updateSelection({id: $scope.lastAddSpecialInvoice.item['invoice_no'], text: $scope.lastAddSpecialInvoice.item['invoice_no']});
                                    dialogScope.data.item.invoice_no = $scope.lastAddSpecialInvoice.item['invoice_no'];
                                    $('#promise_fulfil_principle').data('select2').updateSelection({id: $scope.lastAddSpecialInvoice.item['promise_fulfil_principle'], text: $scope.lastAddSpecialInvoice.item['principal_name']});
                                    dialogScope.data.item.promise_fulfil_principle = $scope.lastAddSpecialInvoice.item['promise_fulfil_principle'];
                                    dialogScope.data.attachmentList = $scope.lastAddSpecialInvoice['attachmentList'];
                                    dialogScope.data.item.promise_fulfil_time = $scope.lastAddSpecialInvoice.item['promise_fulfil_time'];
                                },0);
                            }



                        }
                        else {
                            // 编辑模式
                            var url = api_prefix + "/special-approval-invoice/get-special-approval-invoice-info";
                            util.myAjax({
                                url: url,
                                type: "GET",
                                cache: false,
                                data: {invoiceId: row.special_approval_invoice_id},
                                context: this,
                                success: function(json) {
                                    if (json.retCode == 0) {
                                        for (var attr in json.data.item) {
                                            dialogScope.data.item[attr] = json.data.item[attr];
                                        }

                                        var promiseDate = moment(dialogScope.data.item['promise_fulfil_time'],'YYYY-MM-DD HH:mm:ss');
                                        if(promiseDate.isValid()){
                                            dialogScope.data.item['promise_fulfil_time'] = promiseDate.format('YYYY-MM-DD');
                                        }
                                        var actualDate = moment(dialogScope.data.item['actual_fulfil_time'],'YYYY-MM-DD HH:mm:ss');
                                        if(actualDate.isValid()){
                                            dialogScope.data.item['actual_fulfil_time'] = actualDate.format('YYYY-MM-DD');
                                        }
                                        dialogScope.data.attachmentList = json.data['attachmentList'];
                                        dialogScope.data.item.category_temp = dialogScope.data.item.category;

                                        $('#invoice_no').data('select2').updateSelection({id: dialogScope.data.item['invoice_no'], text: dialogScope.data.item['invoice_no']});
                                        $('#promise_fulfil_principle').data('select2').updateSelection({id: dialogScope.data.item['promise_fulfil_principle'], text: dialogScope.data.item['principal_name']});


                                    } else {
                                        util.alert(json.errMsg);
                                    }
                                },
                                complete: function() {
//                                dialogScope.loading = false;
                                    dialogScope.$applyAsync();
                                    ui.removeLoading();
                                }
                            });
                        }

                        // 上传控件初始化
                        $('#fileupload').fileupload({
                            dataType: 'json',
                            url: api_prefix + "/common/file/upload-document",
                            add: function(e, data) {
                                // 大小限制
                                if(data.files.length>0){
                                    if(data.files[0].size>config.uploader.max_file_size){
                                        util.alert('文件大小超出'+config.uploader.max_file_size_text+'，无法上传。');
                                        return;
                                    }
                                }
                                data.submit();
                                ui.loading('', '正在上传…');
                                $("#fileupload_error").hide();
                            },
                            done: function(e, data) {
                                var res = data.result;
                                if (res.retCode == "0") {
                                    var document = {
                                        document_id: ++$scope.sn,
                                        document_name: data.files[0].name,
                                        document_ext_name: '',
                                        document_path: res.data.path,
                                        business_id: ''
                                    };
                                    dialogScope.data.attachmentList.push(document);
                                    dialogScope.$applyAsync();

                                    $("#fileupload_error").html("");
                                    $("#fileupload_error").hide();
                                } else {
                                    $("#fileupload_error").html("上传失败:" + res.errMsg);
                                    $("#fileupload_error").show();
                                }
                            },
                            fail: function(e, data) {
                                $("#fileupload_error").html("上传失败:" + data.errorThrown);
                                $("#fileupload_error").show();
                            },
                            always: function(e, data) {
                                ui.removeLoading();
                            }
                        });

                    }
                    $scope.getCategoryList = function() {
                        return [
                            {id: 1, value: '合同未归档'},
                            {id: 2, value: '开票金额与合同应收金额不相等'},
                            {id: 3, value: '开票名称与签约客户名称不一致'},
                            {id: 4, value: '结算款未支付'},
                            {id: 5, value: '合同未归档'},
                            {id: 6, value: '开票名称与付款名称不一致'}
                        ];
                    };
                    //删除发票
                    $scope.removeInvoice = function (id) {
                        util.confirm('确定要删除此发票吗？', {
                            ok: function () {
                                var url = api_prefix + '/special-approval-invoice/del-special-approval-invoice';

                                $.ajax({
                                    url: url,
                                    type: 'get',
                                    dataType: 'json',
                                    data: {invoiceId: id},
                                    success: function (res) {
                                        if (res.retCode === "0") {
                                            $scope.query.execute($scope.page_index);
                                            util.alert('删除成功');
                                        }else{
                                            util.alert(res.errMsg);
                                        }
                                    },
                                    error: function () {
                                        util.alert('系统维护，请稍候重试！');
                                    }
                                });
                            }
                        });
                    };
                    $scope.query.execute();
                }]);
});
